

let loadingInstance;

var modal = { //各种弹窗组件
  methods: {
    // 消息提示
    msg(content, domEl) {
      let _that = domEl || top.vm
      _that.$message.info(content)
    },
    // 错误消息
    msgError(content, domEl) {
      let _that = domEl || top.vm
      _that.$message.error(content)
    },
    // 成功消息
    msgSuccess(content, domEl) {
      let _that = domEl || top.vm
      _that.$message.success(content)
    },
    // 警告消息
    msgWarning(content, domEl) {
      let _that = domEl || top.vm
      _that.$message.warning(content)
    },
    // 弹出提示
    alert(content, domEl) {
      let _that = domEl || top.vm
      _that.$messageBox.alert(content, "系统提示")
    },
    // 错误提示
    alertError(content, domEl) {
      let _that = domEl || top.vm
      _that.$messageBox.alert(content, "系统提示", { type: 'error' })
    },
    // 成功提示
    alertSuccess(content, domEl) {
      let _that = domEl || top.vm
      _that.$messageBox.alert(content, "系统提示", { type: 'success' })
    },
    // 警告提示
    alertWarning(content, domEl) {
      let _that = domEl || top.vm
      _that.$messageBox.alert(content, "系统提示", { type: 'warning' })
    },
    // 通知提示
    notify(content, domEl) {
      let _that = domEl || top.vm
      _that.$notification.info(content)
    },
    // 错误通知
    notifyError(content, domEl) {
      let _that = domEl || top.vm
      _that.$notification.error(content);
    },
    // 成功通知
    notifySuccess(content, domEl) {
      let _that = domEl || top.vm
      _that.$notification.success(content)
    },
    // 警告通知
    notifyWarning(content, domEl) {
      let _that = domEl || top.vm
      _that.$notification.warning(content)
    },
    // 确认窗体
    confirm(content, domEl) {
      let _that = domEl || top.vm
      return _that.$confirm(content, "系统提示", {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: "warning",
      })
    },

    // 提交内容
    prompt(content, domEl) {
      let _that = domEl || top.vm
      return _that.$prompt(content, "系统提示", {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: "warning",
      })
    },
    // // 打开遮罩层
    startLoading(content = "加载中", option = {}, domEl) {
      let _that = domEl || top.vm
      loadingInstance = _that.$loading({
        lock: option.lock || true,
        text: content,
        spinner: option.spinner || "el-icon-loading",
        background: option.background || "rgba(0, 0, 0, 0.7)",
        target: option.target || null
      })
    },
    // 关闭遮罩层
    closeLoading() {
      loadingInstance.close();
    },
    getDomClassVal(dom, className_) {
      let classList = Array.from($(dom)[0].classList)
      let ClassVal = "";
      for (let i = 0; i < classList.length; i++) {
        const className = classList[i];
        if (className.indexOf(className_) != -1) { ClassVal = className.replace(className_, "") }
      }
      return ClassVal;
    },
    openDetailsWin(option) {
      let p = ""
      if (option.params && Object.keys(option.params).length) {
        for (const key in option.params) {
          const item = option.params[key];
          p += "&" + key + "=" + item
        }
        if (option.iframeUrl) {
          if (option.iframeUrl.indexOf("?") != -1) {
            p = p.replace("&", "");
          } else {
            p = p.replace("&", "?");
          }
          option.iframeUrl += p;
        }
      }
      top.$("body").append('<iframe src="' + option.iframeUrl + '" frameborder="0" class="PopupFrame" id="iframe_' + option.id + '"></iframe>')
      top.$("#iframe_" + option.id)[0].contentWindow.name = option.id;
    },
    CL(id) {
      top.$("#iframe_" + (id || window.name)).remove();
    },
    Refresh(type, id) {
      let iframeName = id ? ("iframe_" + id) : "lay-iframe";
      eval(`top.$("#${iframeName}")[0].contentWindow.${type}`)
    },
    getDictionary(score, id, val, returnval) {
      console.log(score);
      for (let i = 0; i < score.length; i++) {
        const element = score[i];
        if (element[id] == val) {
          return element[returnval]
        }
      }
    },
    // 保留两位小数
    formatNum(val, key) {
      let checkPlan = '' + val
      checkPlan = checkPlan
        .replace(/[^\d.]/g, '') // 清除“数字”和“.”以外的字符
        .replace(/\.{2,}/g, '.') // 只保留第一个. 清除多余的
        .replace(/^\./g, '') // 保证第一个为数字而不是.
        .replace('.', '$#$')
        .replace(/\./g, '')
        .replace('$#$', '.')
      if (checkPlan.indexOf('.') < 0 && checkPlan !== '') {
        // 以上已经过滤，此处控制的是如果没有小数点，首位不能为类似于 01、02的金额
        checkPlan = parseFloat(checkPlan) + ''
      } else if (checkPlan.indexOf('.') >= 0) {
        checkPlan = checkPlan
          .replace(/^()*(\d+)\.(\d\d).*$/, '$1$2.$3') // 只能输入两个小数
      }
      this.form[key] = Number(checkPlan).toFixed(2);
    },
  }
}

var Ajax = {
  data() {
    return {
      loginUrlPc: '/web/login.html',
      homeUrlPc: '/web/layout/index.html',
    }
  },
  methods: {
    AJAX: function (option, callBack) {
      // 默认全局请求头选项
      let setupHeader = function () {
        let headers = {}
        if (option.headers) {
          headers = option.headers
        } else if (!option.devType) {
          headers = { "token": Pms.getToken() }
        }
        if (!option.uploadImg && !option.headers) { headers['Content-type'] = option.ContentType }
        return headers;
      }
      // 请求过滤
      $.ajaxPrefilter(function (options) {
        let url = options.url;
        if (url.indexOf("http://") == -1 && url.indexOf("https://") == -1) {
          options.url = Config.PmsUrl + url;
        }
      });
      // 返回ajax数据
      return new Promise((resolve, reject) => {
        $.ajax({
          type: option.method,  //默认get
          url: option.url,  //默认当前页
          data: option.map || "",  //格式{key:value}
          async: true,
          cache: option.cache || false,
          contentType: option.uploadImg ? false : undefined,
          processData: option.uploadImg ? false : undefined,
          headers: setupHeader(),
          dataType: "json",
          beforeSend: (xhr) => {
            //请求发送前回调,常用验证
            xhr.then((res, status) => {
              // 如果是微信调用接口
              if (res.retcode && res.retcode == 999999) {
                this.msgError("程序异常")
                return;
              }

              if (status.indexOf("error") != -1) {
                this.msgError("程序异常")
                reject(e)
                return;
              }

              if (status == "parsererror") {
                this.msgError("返回数据类型错误")
                reject(e)
                return;
              }
              //如果没有传入设备类型，默认pc
              if (!option.devType) {
                if (res.retcode && res.retcode == 5005003) {
                  this.msgError("登录超时, 请从新登陆")
                  setTimeout(() => {
                    top.location.replace(this.loginUrlPc);
                  }, 2000);
                  return;
                }

                if (!localStorage['token'] && res.retcode && res.retcode == 500 && Pms.isLoginPage()) {
                  this.msgError("登录超时, 请从新登陆")
                  setTimeout(() => {
                    top.location.replace(this.loginUrlPc);
                  }, 2000);
                  return;
                }

                if (res.retmsg && res.retmsg.indexOf("the user expired") != -1 && Pms.isLoginPage()) {
                  this.msgError("登录超时, 请从新登陆")
                  setTimeout(() => {
                    top.location.replace(this.loginUrlPc);
                  }, 2000);
                  return;
                }

                if (res.retmsg && res.retmsg.indexOf("the user is not exist") != -1 && Pms.isLoginPage()) {
                  this.msgError("用户不存在，请重新登录")
                  setTimeout(() => {
                    top.location.replace(this.loginUrlPc);
                  }, 2000);
                  return;
                }
              }
            })

          },
          success: function (response) {  //请求成功回调
            if (callBack) { callBack(response); } else { resolve(response) }
          },
          error: (e) => {  //请求超时回调
            reject(e)
            if (e.status == 404) {
              this.msgError('找不到该接口')
              return;
            } else if (e.status == 500) {
              this.msgError('服务器内部错误')
              return;
            } else if (e.status == 400) {
              this.msgError('参数类型传递错误')
              return;
            } else {
              this.msgError('请求异常，找不到服务器')
            }
          },
          complete: function () { }, //无论请求是成功还是失败都会执行的回调，常用全局成员的释放，或者页面状态的重置
        })
      })
    },

    /**
     * POST 方式发送接口请求
     * @param {Object} option 
     * @param {Function} callBack 
     */
    POST: function (option, callBack) {
      // option.map = Pms.getSessionId(option.map);
      if (option.url == undefined) {
        this.msgError("缺少参数：url");
      } else {
        option["method"] = "POST";
        option.ContentType = option.ContentType ? option.ContentType : "application/x-www-form-urlencoded; charset=UTF-8"
        return this.AJAX(option, callBack);
      }
    },
    /**
     * APP GET 方式发送接口请求
     * @param {Object} option 
     * @param {Function} callBack 
     */
    GET: function (option, callBack) {
      if (option.url == undefined) {
        this.msgError("缺少参数：url");
      } else {
        option["method"] = "GET";
        option.ContentType = "application/json;charset=UTF-8"
        return this.AJAX(option, callBack);
      }
    },
  }
}